import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

class NFCUtils {
  static const MethodChannel _channel = MethodChannel('app.nfc/channel');
  static StreamController<String>? _tagStreamController;

  static Future<void> _initNfcListener() async {
    if (_tagStreamController != null) return;

    _tagStreamController = StreamController<String>.broadcast();
    _channel.setMethodCallHandler((call) async {
      if (call.method == 'onTagDiscovered') {
        String tagId = call.arguments as String;
        _tagStreamController?.add(tagId);
      }
    });
  }

  /// 检查NFC是否可用
  static Future<bool> checkNFCAvailability(BuildContext context) async {
    try {
      await _initNfcListener();
      final bool isAvailable = await _channel.invokeMethod('isNfcAvailable');
      if (!isAvailable) {
        EasyLoading.showError('NFC不可用，请确保设备支持NFC并已开启');
        return false;
      }
      return true;
    } on PlatformException catch (e) {
      debugPrint('NFC检查出错: $e');
      EasyLoading.showError('NFC功能检查失败');
      return false;
    }
  }

  /// 启动NFC扫描
  static Future<String?> startNFCScanning() async {
    try {
      await _initNfcListener();
      EasyLoading.show(status: '请将IC卡贴近手机背面...');
      
      // 告诉原生层我们要开始读卡
      await _channel.invokeMethod('readTag');
      
      // 等待NFC卡片被读取
      String? cardId = await _tagStreamController?.stream.first
          .timeout(const Duration(seconds: 30), onTimeout: () {
        EasyLoading.showError('扫描超时，请重试');
        return '';
      });
      
      if (cardId != null && cardId.isNotEmpty) {
        return cardId;
      } else {
        EasyLoading.showError('未能获取卡号');
        return null;
      }
    } on PlatformException catch (e) {
      debugPrint('启动NFC扫描出错: $e');
      EasyLoading.showError('NFC扫描失败: ${e.message}');
      return null;
    } catch (e) {
      debugPrint('NFC扫描异常: $e');
      EasyLoading.showError('NFC扫描出错，请重试');
      return null;
    } finally {
      EasyLoading.dismiss();
    }
  }

  /// 释放资源
  static void dispose() {
    _tagStreamController?.close();
    _tagStreamController = null;
  }
} 